import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';
import '../../providers/user_provider.dart';
import '../../providers/auth_provider.dart';
import '../../providers/version_provider.dart';

class ProfilePage extends StatelessWidget {
  const ProfilePage({super.key});

  void _showRoleSwitchDialog(BuildContext context, UserProvider userProvider) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('切换身份'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: userProvider.roles
              .map((item) => ListTile(
                    title: Text(item == 'fisher'
                        ? '钓友'
                        : item == 'manager'
                            ? '管理员'
                            : '创始人'),
                    onTap: () {
                      userProvider.switchRole(item);
                      Navigator.pop(context);
                    },
                  ))
              .toList(),
        ),
      ),
    );
  }

  void _checkForUpdates(BuildContext context) {
    final versionProvider = context.read<VersionProvider>();
    
    // 显示检查中的提示
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Row(
          children: [
            SizedBox(
              width: 16,
              height: 16,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),
            SizedBox(width: 12),
            Text('正在检查更新...'),
          ],
        ),
        duration: Duration(seconds: 2),
      ),
    );

    // 强制检查更新
    versionProvider.checkUpdate(forceCheck: true, showNoUpdateMessage: true);
    
    // 监听检查结果
    void listener() {
      if (!versionProvider.isChecking) {
        versionProvider.removeListener(listener);
        
        if (versionProvider.errorMessage != null) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(versionProvider.errorMessage!),
              backgroundColor: versionProvider.errorMessage!.contains('最新版本') 
                  ? Colors.green 
                  : Colors.red,
            ),
          );
          versionProvider.clearError();
        }
      }
    }
    
    versionProvider.addListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);
    final user = userProvider.user;
    final roles = userProvider.roles;

    return Scaffold(
      extendBody: true, // 推荐开启
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人中心'),
        actions: [
          TextButton(
            onPressed: () async {
              // 显示确认对话框
              final bool? confirm = await showDialog<bool>(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('确认退出'),
                  content: const Text('确定要退出登录吗？'),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context, false),
                      child: const Text('取消'),
                    ),
                    TextButton(
                      onPressed: () => Navigator.pop(context, true),
                      child: const Text('确定'),
                    ),
                  ],
                ),
              );

              if (confirm == true) {
                // 清除本地存储的token和用户信息
                // ignore: use_build_context_synchronously
                final authProvider = Provider.of<AuthProvider>(context, listen: false);
                final userProvider = Provider.of<UserProvider>(context, listen: false);
                
                try {
                  debugPrint('开始退出登录流程');
                  
                  // 1. 执行登出操作（会清除token和设置登录状态）
                  await authProvider.logout();
                  debugPrint('认证状态已清除');
                  
                  // 2. 清除用户信息
                  userProvider.clearUser();
                  debugPrint('用户信息已清除');
                  
                  // 3. 等待状态更新传播
                  await Future.delayed(const Duration(milliseconds: 100));
                  
                  // 4. 强制跳转到登录页
                  if (context.mounted) {
                    debugPrint('准备跳转到登录页');
                    context.go('/login');
                  }
                  
                } catch (e) {
                  debugPrint('退出登录过程中出错: $e');
                  // 即使出错也要清除状态并跳转
                  userProvider.clearUser();
                  authProvider.setLoggedIn(false);
                  
                  if (context.mounted) {
                    context.go('/login');
                  }
                }
              }
            },
            child: const Text(
              '退出登录',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
      body: CustomScrollView(
        physics: const ClampingScrollPhysics(),
        slivers: [
          // 顶部个人信息卡片
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(30),
                  bottomRight: Radius.circular(30),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.blue.withAlpha((0.1 * 255).round()),
                    blurRadius: 10,
                    offset: const Offset(0, 5),
                  ),
                ],
              ),
              child: Column(
                children: [
                  const SizedBox(height: 40),
                  // 头像
                  CircleAvatar(
                    radius: 50,
                    backgroundColor: Colors.white,
                    child: user?.avatar != null
                        ? ClipOval(
                            child: Image.network(
                              user!.avatar!,
                              width: 100,
                              height: 100,
                              fit: BoxFit.cover,
                            ),
                          )
                        : const Icon(
                            Icons.person,
                            size: 50,
                            color: Colors.blue,
                          ),
                  ),
                  const SizedBox(height: 16),
                  // 用户名
                  Text(
                    user?.nickName ?? '未登录',
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  const SizedBox(height: 8),
                  // 用户角色标签
                  if (roles.isNotEmpty)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 6,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white..withAlpha((0.2 * 255).round()),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        roles.first == 'fisher' ? '伟大的钓手' : "管理员",
                        style: const TextStyle(
                          color: Colors.blue,
                          fontSize: 14,
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),

          // 功能菜单
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 100), // 增加底部padding避免被底部导航栏挡住
              child: Column(
                children: [
                  _buildMenuSection(
                    context,
                    title: '我的服务',
                    items: [
                      _MenuItem(
                        icon: Icons.history,
                        title: '钓鱼记录',
                        onTap: () {
                          // TODO: 导航到钓鱼记录页面
                        },
                      ),
                      _MenuItem(
                        icon: Icons.favorite,
                        title: '我的收藏',
                        onTap: () {
                          context.push('/profile/favorites');
                        },
                      ),
                      _MenuItem(
                        icon: Icons.star,
                        title: '我的评价',
                        onTap: () {
                          context.push('/profile/reviews');
                        },
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  _buildMenuSection(
                    context,
                    title: '其他',
                    items: [
                      _MenuItem(
                        icon: Icons.settings,
                        title: '个人信息修改',
                        onTap: () {
                          context.push('/profile/account');
                        },
                      ),
                      if (roles.contains('manager'))
                      _MenuItem(
                          icon: Icons.swap_horiz,
                          title: '切换身份',
                          onTap: () =>
                              _showRoleSwitchDialog(context, userProvider),
                        ),
                      _MenuItem(
                        icon: Icons.help_outline,
                        title: '帮助中心',
                        onTap: () {
                          context.push('/profile/help');
                        },
                      ),
                      _MenuItem(
                        icon: Icons.system_update,
                        title: '检查更新',
                        onTap: () => _checkForUpdates(context),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMenuSection(
    BuildContext context, {
    required String title,
    required List<_MenuItem> items,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.blue.withAlpha((0.1 * 255).round()),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          const Divider(height: 1),
          ...items.map((item) => _buildMenuItem(context, item)),
        ],
      ),
    );
  }

  Widget _buildMenuItem(BuildContext context, _MenuItem item) {
    return InkWell(
      onTap: item.onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          children: [
            Icon(
              item.icon,
              color: Colors.blue,
              size: 24,
            ),
            const SizedBox(width: 16),
            Text(
              item.title,
              style: const TextStyle(
                fontSize: 16,
              ),
            ),
            const Spacer(),
            const Icon(
              Icons.chevron_right,
              color: Colors.grey,
            ),
          ],
        ),
      ),
    );
  }
}

class _MenuItem {
  final IconData icon;
  final String title;
  final VoidCallback onTap;

  const _MenuItem({
    required this.icon,
    required this.title,
    required this.onTap,
  });
}
